----------------------------------------------------------------------------------
-- Company: 
-- Engineer: 
-- 
-- Create Date:    13:56:49 03/08/2012 
-- Design Name: 
-- Module Name:    ADC_State_Machine - Behavioral 
-- Project Name: 
-- Target Devices: 
-- Tool versions: 
-- Description: 
--
-- Dependencies: 
--
-- Revision: 
-- Revision 0.01 - File Created
-- Additional Comments: 
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity ADC_accell is
    Port ( 
		clk_in		: in  STD_LOGIC;	-- input clk, twice frequency of output clock	
		eoc			: in  STD_LOGIC;	-- end of conversion, will be sent out as oe
		clk_out		: out STD_LOGIC;  -- clock out, half of input frequency
		oe				: out std_logic;  -- output enable
		start			: out STD_LOGIC;  -- start signal, will be timed to be eoc
		addrA			: out STD_LOGIC;  -- address A input, will toggle between potentiometers
		ale			: out STD_LOGIC;	-- address latch enable, toggled high when correct address is sent
		data_ready	: out std_logic	-- signal to rest of system that ADC data should be here
	 );
end ADC_accell;

architecture Behavioral of ADC_accell is
	signal C_S		: integer range 1 to 10:=1; -- current state
	signal N_S		: integer range 1 to 10:=1; -- next state
	
	signal addrA_current, addrA_next : std_logic := '0';
	
begin

	clk_out <= clk_in;
	
	
	Clock:
	process(clk_in)
	begin
		if rising_edge(clk_in) then
			C_S <= N_S;
			addrA_current <= addrA_next;
		end if;
	end process;
	States:
	process (C_S, eoc)
	begin
		--Default
	
		if (C_S = 1) then
			--addrA <= '0'; -- input selected
			N_S <= 2;
			--ale <= '0';
			--start <= '0';
			--oe <= '0';
		elsif (C_S = 2) then
			--ale <='1';
			N_S <= 3;
		elsif (C_S = 3) then
			--ale <='1';
			--start <='1';
			N_S <= 4;
		elsif (C_S = 4) then
			--ale <='0';
			--start <='1';
			N_S <= 5;
		elsif (C_S = 5) then			
			--start <='0';
			if eoc = '1' then
				N_S <= 6;
			else
				N_S <= 5;
			end if;
		elsif (C_S = 6) then
				--oe <= '1';
				N_S <= 7;
		elsif (C_S = 7) then
			N_S <= 8;
		elsif (C_S = 8) then
			N_S <= 9;
		elsif (C_S = 9) then
			N_S <= 10;
		elsif (C_S = 10) then
		--	oe <= '0';
			N_S <= 1;			
		end if;		
	end process;
	
	ale <= '1' when C_S = 2 or C_S = 3 else '0';
	start <= '1' when C_S = 3 or C_S = 4 else '0';
	oe <= '1' when C_S = 6 or C_S = 7 or C_S = 8 or C_S = 9 else '0';
	data_ready <= '1' when C_S = 8 else '0';
	
	with C_S select addrA_next <= 
		not addrA_current when 9,
		addrA_current when others;
	
	addrA <= addrA_current;

end Behavioral;